package com.zsg.androidsipphone.util;

import okhttp3.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 描述：okHttp3请求
 *
 * @author zsg
 */

public class OkHttpUtil {

    /**
     * Get请求连接
     *
     * @param uri 请求API
     * @return 字符串数据
     * */
    public static String doGet(String uri) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(uri)
                .get()  //默认为GET请求，可以不写
                .build();
        Response response = client.newCall(request).execute();
        assert response.body() != null;
        if(response.code() == 200) {
            return response.body().string();
        }
        return "error:"+response.code();
    }

    /**
     * Post提交数据
     *
     * @param uri 请求API
     * @param json 要上传的json数据
     * @return 字符串数据
     * */
    public static String doPost(String uri, String json) throws IOException {
        //构建一个RequestBody对象,,因为提交的是json字符串需要添加一个MediaType为"application/json",
        // 普通的字符串直接是null就可以了
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), json);

        Response response = client.newCall(new Request.Builder()
                .url(uri)
                .post(requestBody)
                .build())
                .execute();
        assert response.body() != null;
        if(response.code() == 200) {
            return response.body().string();
        }
        return "error:"+response.code();
    }

    /**
     * Post提交数据
     *
     * @param uri 请求API
     * @param formBody 要上传的表单
     * FormBody.Builder builder = new FormBody.Builder();
     * builder.add("name", "zsg");
     * builder.add("age", "18");
     * FormBody formBody = builder.build();
     * @return 字符串数据
     * */
    public static String doPost(String uri, FormBody formBody) throws IOException {
        Request request = new Request.Builder()
                .url(uri)
                .post(formBody)
                .build();
        Response response = new OkHttpClient().newCall(request).execute();
        assert response.body() != null;
        if(response.code() == 200) {
            return response.body().string();
        }

        return "error:"+response.code();
    }

    /**
     * Post提交数据
     *
     * @param uri 请求API
     * @param multipartBody 要上传的 MultipartBody 数据
     * MultipartBody multipartBody = new MultipartBody.Builder()
     *      .setType(MultipartBody.FORM)
     *      .addFormDataPart("name", "zsg")
     *      .addFormDataPart("age", "20")
     *      .addFormDataPart("icon", icon.getName(),
     *          RequestBody.create(MediaType.parse("application/octet-stream"), icon))
     *       .build();
     * @return 字符串数据
     * */
    public static String doPost(String uri, MultipartBody multipartBody) throws IOException {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(uri)
                .post(multipartBody)
                .build();
        Response response = client.newCall(request).execute();
        assert response.body() != null;
        if(response.code() == 200) {
            return response.body().string();
        }
        return "error:"+response.code();
    }

    /**
     * 上传文件
     *
     * @param uri 请求API
     * @param filePath 要上传文件的本地路径
     * @return 字符串数据
     * */
    public static String uploadFile(String uri, String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            return "no file!";
        }
        OkHttpClient client = new OkHttpClient();

        RequestBody requestBody =  RequestBody.create(MediaType.parse("application/octet-stream"), file);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(uri)
                .build();

        Response response = client.newCall(request).execute();
        assert response.body() != null;
        if(response.code() == 200) {
            return response.body().string();
        }
        return "error:"+response.code();
    }

    /**
     * 下载文件
     *
     * @param uri 请求API
     * @param savePath 下载文件的本地保存路径
     * @return 字符串数据
     * */
    public static boolean downloadFile(String uri, String savePath) throws IOException {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(uri)
                .build();
        Response response = client.newCall(request).execute();
        if(response.code() == 200){

            InputStream is;
            FileOutputStream fos;
            byte[] buf = new byte[2048];
            int len;

            try {
                File file = new File(savePath);
                assert response.body() != null;
                is = response.body().byteStream();
                //写入文件
                fos = new FileOutputStream(file);
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
                fos.close();
                is.close();

                return true;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return false;
    }

}
